package com.rzico.sbl.ui.report.dispatch

import android.text.InputFilter
import android.widget.EditText
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.lifecycleScope
import com.jeremyliao.liveeventbus.LiveEventBus
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportEndBucketBinding
import com.rzico.sbl.model.DispatchBucket
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.other.DecimalNumberFilter
import com.xinnuo.common_ui.base.BaseActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.math.abs

class ReportEndBucketActivity : BaseActivity(R.layout.activity_report_end_bucket) {

    private val mBinding by lazy { ActivityReportEndBucketBinding.bind(getRootView()) }

    private lateinit var mItemData: DispatchBucket

    override fun initData() {
        initTitle(title = "空桶编辑")

        // 入库赋值会计算欠桶和还桶
        mBinding.bucketIn.setText(mItemData.returnQuantity.orEmpty("0"))
    }

    override fun initListener() {
        mItemData = intent.getParcelableExtra("data")!!

        mBinding.apply {
            mItemData.also {
                if (it.quantity.intValue == 0) bucketOther.gone()

                // 以往欠桶
                if (it.borrow.intValue > 0) bucketOld.setText(it.borrow)
                // 司机还桶
                if (it.backQuantity.intValue > 0) bucketDriver.setText(it.backQuantity)

                // 送出桶
                if (it.quantity.intValue > 0) bucketOut.setText(it.quantity)

                // 押桶
                bucketYa.text = it.pledgeQuantity.orEmpty("0")
                bucketMoney2.text = it.pledge.formatDecimal()

                // 买桶
                bucketMai.text = it.buyQuantity.orEmpty("0")
                bucketMoney3.text = it.buy.formatDecimal()

                // 退桶
                bucketTui.text = it.refundsQuantity.orEmpty("0")
                bucketMoney4.text = it.refunds.formatDecimal()

                // 兑换桶
                bucketChange.text = it.transQuantity.orEmpty("0")
                if (it.transQuantity.intValue > 0) bucketExpand.expand()
                // 外品牌1:1
                if (it.percent1.intValue > 0) bucketOne.setText(it.percent1)
                // 外品牌2:1
                if (it.percent2.intValue > 0) bucketTwo.setText(it.percent2)
                // 外品牌3:1
                if (it.percent3.intValue > 0) bucketThree.setText(it.percent3)
                // 外品牌补差价
                bucketFill.text = it.percent4.orEmpty("0")
                bucketMoney1.text = it.differPrice.formatDecimal()

                // 备注
                bucketMemo.setText(it.memo1.orEmpty())
            }

            bucketMoney1.filters = arrayOf(DecimalNumberFilter(), InputFilter.LengthFilter(8))
            bucketMoney2.filters = arrayOf(DecimalNumberFilter(), InputFilter.LengthFilter(8))
            bucketMoney3.filters = arrayOf(DecimalNumberFilter(), InputFilter.LengthFilter(8))
            bucketMoney4.filters = arrayOf(DecimalNumberFilter(), InputFilter.LengthFilter(8))

            bucketDriver.doAfterTextChanged { totalIn() }    //司机还桶
            bucketOut.doAfterTextChanged { totalIn() }       //送出桶
            bucketIn.doAfterTextChanged { totalIn() }        //入库
            bucketYa.doAfterTextChanged { totalIn() }        //押桶
            bucketMai.doAfterTextChanged { totalIn() }       //买桶
            bucketTui.doAfterTextChanged { totalIn() }       //退桶
            bucketChange.doAfterTextChanged { totalIn() }    //兑换桶

            bucketOne.doAfterTextChanged { totalChange() }   //外品牌1:1
            bucketTwo.doAfterTextChanged { totalChange() }   //外品牌2:1
            bucketThree.doAfterTextChanged { totalChange() } //外品牌3:1
            bucketFill.doAfterTextChanged { totalChange() }  //外桶补差价

            // 外品牌2比1 焦点监听
            bucketTwo.setOnFocusChangeListener { view, hasFocus ->
                (view as EditText)
                    .content
                    .apply {
                        if (!hasFocus
                            && isNotEmpty()
                            && intValue % 2 != 0
                        ) longToast("外品牌2:1 只能输入2的倍数")
                    }
            }

            // 外品牌3比1 焦点监听
            bucketThree.setOnFocusChangeListener { view, hasFocus ->
                (view as EditText)
                    .content
                    .apply {
                        if (!hasFocus
                            && isNotEmpty()
                            && intValue % 3 != 0
                        ) longToast("外品牌3:1 只能输入3的倍数")
                    }
            }

            // 兑换桶展开/折叠
            bucketChangeLl.oneClick {
                if (bucketExpand.isExpanded) {
                    bucketExpand.collapse()
                    bucketChangeArrow.startRotateAnimator(90f, 0f)
                } else {
                    bucketExpand.expand()
                    bucketChangeArrow.startRotateAnimator(0f, 90f)
                }
            }

            // 保存编辑
            btSave.oneClick {
                val countTwo = bucketTwo.textInt
                val ocountThree = bucketThree.textInt

                when {
                    countTwo % 2 != 0 -> {
                        showToast("外品牌2:1 只能输入2的倍数")
                        bucketTwo.requestFocus()
                        return@oneClick
                    }
                    ocountThree % 3 != 0 -> {
                        showToast("外品牌3:1 只能输入3的倍数")
                        bucketThree.requestFocus()
                        return@oneClick
                    }
                }

                mItemData.also {
                    it.borrow = bucketOld.textOrEmpty("0")
                    it.backQuantity = bucketDriver.textOrEmpty("0")

                    it.quantity = bucketOut.textOrEmpty("0")
                    it.returnQuantity = bucketIn.textOrEmpty("0")

                    it.arrearsQuantity = bucketQian.content
                    it.repayQuantity = bucketHuan.content

                    if (bucketYa.textInt > 0) {
                        it.pledgeQuantity = bucketYa.content
                        it.pledge = bucketMoney2.content.formatDecimal()
                    } else {
                        it.pledgeQuantity = "0"
                        it.pledge = "0.00"
                    }

                    if (bucketMai.textInt > 0) {
                        it.buyQuantity = bucketMai.content
                        it.buy = bucketMoney3.content.formatDecimal()
                    } else {
                        it.buyQuantity = "0"
                        it.buy = "0.00"
                    }

                    if (bucketTui.textInt > 0) {
                        it.refundsQuantity = bucketTui.content
                        it.refunds = bucketMoney4.content.formatDecimal()
                    } else {
                        it.refundsQuantity = "0"
                        it.refunds = "0.00"
                    }

                    it.transQuantity = bucketChange.content
                    it.percent1 = bucketOne.textOrEmpty("0")
                    it.percent2 = bucketTwo.textOrEmpty("0")
                    it.percent3 = bucketThree.textOrEmpty("0")
                    it.percent4 = bucketFill.textOrEmpty("0")
                    it.differPrice = bucketMoney1.textOrEmpty("0.00")

                    it.memo1 = bucketMemo.content
                }

                intent
                    .getIntExtra("index", -1)
                    .also {
                        if (it > -1) mItemData.position = it
                        LiveEventBus
                            .get("endFirst")
                            .post(mItemData)
                    }

                finishView()
            }
        }
    }

    /**
     * 兑换桶计算
     */
    private fun totalChange() {
        mBinding
            .apply {
                val countOne = bucketOne.textInt
                val countTwo = bucketTwo.textInt / 2
                val ocountThree = bucketThree.textInt / 3
                val ocountFill = bucketFill.textInt

                bucketChange.text = (countOne + countTwo + ocountThree + ocountFill).toString()
            }
    }

    /**
     * 入库计算
     */
    private fun totalIn() {
        mBinding.apply {
            lifecycleScope.launch(Dispatchers.IO) {
                val countDriver = bucketDriver.textInt
                val countOut = bucketOut.textInt
                val countIn = bucketIn.textInt
                val countYa = bucketYa.textInt
                val countMai = bucketMai.textInt
                val countTui = bucketTui.textInt
                val countChange = bucketChange.textInt

                val totalCount =
                    countOut - countIn - countDriver - countYa - countMai + countTui - countChange

                withContext(Dispatchers.Main) {
                    when {
                        totalCount > 0 -> {
                            bucketQian.text = totalCount.toString()
                            bucketHuan.text = "0"
                        }
                        totalCount < 0 -> {
                            bucketQian.text = "0"
                            bucketHuan.text = abs(totalCount).toString()
                        }
                        else -> {
                            bucketQian.text = "0"
                            bucketHuan.text = "0"
                        }
                    }
                }
            }
        }
    }

}